package com.tbynet.jwp.framework.base;

import java.util.regex.Pattern;

import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.render.JsonRender;

public class BaseController extends Controller {
	
	public void ok(Ret ret) {
		render(new JsonRender(ret.setOk()).forIE());
	}

	public void fail(Ret ret) {
		render(new JsonRender(ret.setFail()).forIE());
	}
	
	public void fail(String msg) {
		fail(Ret.by("msg", msg));
	}
	
	public void json(Ret ret) {
		render(new JsonRender(ret).forIE());
	}
	
	/*
	 * 获取user agent
	 */
	public String getUserAgent() {
		return getHeader("user-agent").toLowerCase();
	}
	
	/*
	 * 根据user agent获取客户端
	 */
	public boolean getClient(String label) {		
		return Pattern.compile(label + "/([^\\s\\_\\-]+)").matcher(getUserAgent()).find();
	}
	
	/*
	 * 是否微信端
	 */
	public boolean isWeixin() {
		return getClient("micromessenger");
	}
	
	/*
	 * 是否ios端
	 */
	public boolean isIos() {
		return Pattern.compile("iphone|ipod|ipad|ios").matcher(getUserAgent()).find();
	}
	
	/*
	 * 是否android端
	 */
	public boolean isAndroid() {
		return Pattern.compile("android").matcher(getUserAgent()).find();
	}
		
	/*
	 * 是否get请求
	 */
	public boolean isGet() {
		return "GET".equalsIgnoreCase(getRequest().getMethod());
	}

	/*
	 * 是否post请求
	 */
	public boolean isPost() {
		return "POST".equalsIgnoreCase(getRequest().getMethod());
	}
	
	/*
	 * 是否ajax请求
	 */
	public boolean isAjax() {
		return "XMLHttpRequest".equals(getHeader("X-Requested-With"));
	}
	
}
